package com.cykj.v_m_sprintboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cykj.v_m_sprintboot.bean.TbOperator;
import com.cykj.v_m_sprintboot.service.TbOpratorService;
import com.sun.org.apache.bcel.internal.generic.L2I;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author: wei
 * @date: 2021/10/6 20:20
 */

@RestController
public class SmsSample {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 注意大写HH是24小时制//小写hh是12小时制
    String time = df.format(new Date());


    @Autowired
    private TbOpratorService tbOpratorService;
    int codeLength = 6;
    String code = "";

    public void RandomCode() {
        Random random = new Random();
        if (code.equals("")) {
            for (int i = 0; i < codeLength; i++) {
                code += String.valueOf(random.nextInt(10));
            }
        }
    }

    public void freshCode() {
        if (!(code.equals(""))) {
            code = "";
            RandomCode();
        }
    }

    @RequestMapping("sendcode")
    @ResponseBody
    public String code(@RequestBody TbOperator tbOperator) {
        //查找该电话是不是以及被注册
        List<TbOperator> telYN = tbOpratorService.findPhone(tbOperator.getOperatorPhone());
        System.out.println("");
        if (tbOperator.getOperatorPhone().equals("")) {
            System.out.println("我进来走2了吗");
            return "2";

        } else if(telYN.size() != 0){
            System.out.println("我进来走3了吗");
            return "3";//电话已经存在，无法注册，换号注册
        }else {
            System.out.println("我进来走1了吗");
            RandomCode();
            freshCode();
            System.out.println(code);
            System.out.println("我来获取验证码了888888888888");
            String testContent = "【传一自动售卖机】您的验证码是" + code + ",3分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
//            System.out.println(testContent);
////		    System.out.println("code是多少"+RandomCode());
//            String testUsername = "wyxcqe"; //在短信宝注册的用户名
//            String testPassword = "wyx,103321"; //在短信宝注册的密码
//            String testPhone = tbOperator.getOperatorPhone();
//            System.out.println(testPhone);
//
//            String httpUrl = "http://api.smsbao.com/sms";
//            StringBuffer httpArg = new StringBuffer();
//            httpArg.append("u=").append(testUsername).append("&");
//            httpArg.append("p=").append(md5(testPassword)).append("&");
//            httpArg.append("m=").append(testPhone).append("&");
//            httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));
//            String result = request(httpUrl, httpArg.toString());
//            System.out.println(result);
//	String SCode =code;
//		System.out.println(code);
            System.out.println(testContent);

            return "1";
        }
    }


    @RequestMapping("/insertOperter")
    @ResponseBody
    public String insertOperter(@RequestBody TbOperator tbOperator) {
        System.out.println(tbOperator.getOperatorAccount() + "pppp--" + tbOperator.getOperatorName());
        System.out.println("时间" + time);
        String qdcode = tbOperator.getVerification();
        System.out.println("前端传来验证码////" + qdcode);
        System.out.println("真机验证码////" + code);
        System.out.println("传来的密码是多少--"+tbOperator.getOperatorPassword());
        String str = "";
        if (!qdcode.equals(code)) {
            System.out.println("验证码错误:" + "前台--" + qdcode + "真机验证码--" + code);
            str = JSON.toJSONString("1");
            return str;
        } else {
            tbOpratorService.insertOperter(tbOperator.getOperatorAccount(), tbOperator.getOperatorPassword(),
                    tbOperator.getOperatorName(), tbOperator.getOperatorPhone(), tbOperator.getOperatorAddress(),
                    tbOperator.getOperatorLicence(), time);
            str = JSON.toJSONString("2");
            return str;
        }

    }

    //运营商登录OpLogin
    @RequestMapping("/OpLogin")
    @ResponseBody
    public String OpLogin(@RequestBody TbOperator tbOperator) {
        String tel = tbOperator.getOperatorPhone();
        String pwd = tbOperator.getOperatorPassword();
        System.out.println("登入电话--"+tel+"登入密码--"+pwd);
        if (!tel.equals("") && !pwd.equals("")) {
            List<TbOperator>   login =    tbOpratorService.OpLogin(tel, pwd);
            if(login.size() != 0){
                System.out.println("我进来验证登入成功");
                return "1";
            }
           return "2";

        } else {


            return "3";
        }
    }

    public String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }
}
